<?php

class importTask extends sfBaseTask
{
  protected function configure()
  {
    // // add your own arguments here
    // $this->addArguments(array(
    //   new sfCommandArgument('my_arg', sfCommandArgument::REQUIRED, 'My argument'),
    // ));

    $this->addArguments(array(
      new sfCommandArgument('database', sfCommandArgument::REQUIRED, 'Old database name'),
      new sfCommandArgument('user', sfCommandArgument::REQUIRED, 'Old database user'),
      new sfCommandArgument('pass', sfCommandArgument::REQUIRED, 'Old database password'),
      new sfCommandArgument('photo-directory', sfCommandArgument::REQUIRED, 'Old photo directory'),
      
      new sfCommandArgument('limit', sfCommandArgument::REQUIRED, ''),
      new sfCommandArgument('offset', sfCommandArgument::REQUIRED, ''),
      // add your own options here
      new sfCommandArgument('application', sfCommandArgument::OPTIONAL, 'The application name','ui')
    ));
    


    $this->namespace        = 'wixet';
    $this->name             = 'import';
    $this->briefDescription = 'Import old wixet database';
    $this->detailedDescription = 'Import old wixet database';
  }

  protected function execute($arguments = array(), $options = array())
  {
    // initialize the database connection
    sfContext::createInstance($this->configuration);
    $databaseManager = new sfDatabaseManager($this->configuration);
	
  	$link =  mysql_connect('localhost', $arguments['user'],  $arguments['pass']);
	if (!$link) {
    	throw new Exception('No pudo conectarse: ' . mysql_error());
	}
	mysql_select_db( $arguments['database'],$link);

    //$this->log("Creating users");
   	//$query = "select * from usuarios LIMIT ".$arguments['offset'].",".$arguments['limit'];
   	
   /*	$query = "SELECT * FROM wixet.usuarios
 where id_usuario not in (SELECT id FROM symfony.sf_guard_user)";*/
   	/*
   	$result = mysql_query($query,$link);
   	while($row = mysql_fetch_assoc($result)){
   		$username = explode("@",$row['email']);
   		$username = $username[0];
   		$this->log( $row['email']." ".$username." ".$row['md5_pass']." ".$row['id_usuario']);
   		try{
   			$this->runTask('guard:create-user', trim($row['email']." ".$username." aaa --id=".$row['id_usuario']));
   		}catch(Exception $e){
   			$username = str_replace("@", "_", $row['email']);
   			$this->runTask('guard:create-user', trim($row['email']." ".$username." aaa --id=".$row['id_usuario']));
   		}
		$user = Doctrine::getTable("sfGuardUser")->findByEmailAddress(trim($row['email']))->getFirst();
		//$user->setId($row['id_usuario']);
		$user->setCreatedAt($row['registro']);
		$user->setFontId($row['id_fuente']);
		$user->setTextColor(str_replace("#","",$row['color_fuente']));
		$user->setFirstname($row['nombre']);
		$user->setLastname($row['apellido1']);
		$user->setSecondlastname($row['apellido2']);
		$user->save();
		
		//Profile
		$profile = $user->getProfile();
		$profile->setBirthday($row['cumple']);
		$profile->setCreatedAt($row['registro']);
		$profile->setVisits($row['visitas']);
		$profile->setCityId($row['id_provincia']);
		$profile->save();
		
		//Blogs
			$blogQuery = "select * from blogs WHERE id_usuario = ".$row['id_usuario']."";
			
   			$blogResult = mysql_query($blogQuery,$link);
   			while($blog = mysql_fetch_assoc($blogResult)){
   				$newBlog = new Blog();
   				$newBlog->setContent($blog['contenido']);
   				$newBlog->setTitle($blog['titulo']);
   				$newBlog->setCreatedAt($blog['fecha']);
   				$newBlog->setProfileId($user->getId());
   				$newBlog->save();
   			}

        		   
		$this->log($user->getUsername()." created");
   	}
   	$this->log("Hecho");
   	mysql_close($link);
return;*/
   	//Comentarios perfil
   	/*$query = "Select * from tablones";
   	$result = mysql_query($query,$link);
	   	while($row = mysql_fetch_assoc($result)){
	   		$comment = new profileComment();
	   		$comment->setOwnerId($row['id_usuario']);
	   		$comment->setAuthorId($row['id_autor']);
	   		$comment->setComment($row['contenido']);
	   		try{
	   			$comment->save();
	   			$comment->setCreatedAt($row['fecha_tablon']);
	   			$comment->save();
	   		}catch(Exception $e){
   				print_r($row);
   				echo "El usuario no existe";
   			}
	   	}

*/
   	//Fotos
/*
   	$query = "SELECT id_usuario from usuarios";
   	$result = mysql_query($query,$link);
   	while($row = mysql_fetch_assoc($result)){
   		echo "Usuario ".$row['id_usuario']."\n";
   		$user = Doctrine::getTable("sfGuardUser")->find($row['id_usuario']);
   		$query2 = "SELECT * from fotos WHERE nombre_foto is not null and id_usuario = ".$row['id_usuario']." ";
   		$result2 = mysql_query($query2,$link);
   		//print_r($user->toArray());
   		$mainAlbum = $user->getMainAlbumId();
   		$mainAlbum = Doctrine::getTable("Album")->find($mainAlbum);
   		while($row2 = mysql_fetch_assoc($result2)){
   			echo "Foto ".$row2['nombre_foto'];
   			$photo = new Photo();
   			$photo->setOwner($user);
   			$photo->setAlbum($mainAlbum);
   			
   			$format = image_type_to_mime_type(exif_imagetype($arguments['photo-directory']."/".$row2['nombre_foto']));
   			
   			if(($format=='image/jpeg') || ($format=='image/png')){
   			$img = null;
   			
	                        if($format=='image/jpeg')
	                        	$img = imagecreatefromjpeg ($arguments['photo-directory']."/".$row2['nombre_foto']);
	                        else
	                        	$img = imagecreatefrompng ($arguments['photo-directory']."/".$row2['nombre_foto']);
	                        
		                        
		                        $name = md5_file($arguments['photo-directory']."/".$row2['nombre_foto']);//Old m5
								$imagePath = sfConfig::get('sf_root_dir')."/photos/tmp_".$name;
		                        //ImagePng($img,$imagePath);
		                        imagejpeg($img,$imagePath);
		                        $name = md5_file($imagePath);
		                        rename($imagePath,sfConfig::get('sf_root_dir')."/photos/".$name);
		                        $imagePath = sfConfig::get('sf_root_dir')."/photos/".$name;
		                        $photo->setPhotoId($name);
		                        try{
		                        $photo->save();
		                        $photo->setCreatedAt($row2['fecha_foto']);
   								$photo->save();
		                        
		                        $normalThumbnail = new sfThumbnail(500, 500);
		                        $listThumbnail = new sfThumbnail(150, 150);
		                        $miniThumbnail = new sfThumbnail(50, 50);
		                        
		  						$normalThumbnail->loadFile($imagePath);
		  						$normalThumbnail->save(sfConfig::get('sf_root_dir')."/photos/thumbnails/normal/".$name, 'image/jpeg');
		                        
		  						$listThumbnail->loadFile($imagePath);
		  						$listThumbnail->save(sfConfig::get('sf_root_dir')."/photos/thumbnails/list/".$name, 'image/jpeg');
		  						
		  						$miniThumbnail->loadFile($imagePath);
		  						$miniThumbnail->save(sfConfig::get('sf_root_dir')."/photos/thumbnails/mini/".$name, 'image/jpeg');

			   		//Etiquetas
				  	$query3 = "Select * from apariciones WHERE id_usuario=".$row2['id_usuario']." and n_foto = ".$row2['n_foto']." ";
				   	$result3 = mysql_query($query3,$link);
				   	
				   	while($row3 = mysql_fetch_assoc($result3)){
				   		$tag = new PhotoTag();
				   		$tag->setHeight($row3['alto']);
				   		$tag->setWidth($row3['ancho']);
				   		$tag->setXPosition($row3['posicion_x']);
				   		$tag->setYPosition($row3['posicion_y']);
				   		$tag->setTaggerId($row3['etiquetado_por']);
				   		$tag->setUserId($row3['id_aparicion']);
				   		$tag->setPhotoId($name);
				   		$tag->setNote($row3['texto']);
				   		$tag->save();
				   	}
				   	//Comentarios photos
				   	$queryCom = "Select * from comentarios WHERE id_usuario=".$row2['id_usuario']." and n_foto = ".$row2['n_foto']." ";
				   	$resultCom = mysql_query($queryCom,$link);
				   	while($rowCom = mysql_fetch_assoc($resultCom)){
				   		$comment = new PhotoComment();
				   		$comment->setUserId($rowCom['id_comentador']);
				   		$comment->setComment($rowCom['comentario']);
				   		$comment->setPhotoId($name);
				   		$comment->save();
				   		$comment->setCreatedAt($rowCom['fecha']);
				   		$comment->save();
				   	}
		                        }catch(Exception $e){
		                        	echo $e->getMessage();
		                        }
   			}else echo "No jpg photo";
   		}	
   		
	   	
   	}   
*/
/*
   	//Friends
   	$query = "Select * from amigos";
   	$result = mysql_query($query,$link);
   	while($row = mysql_fetch_assoc($result)){
   		$user = Doctrine::getTable("sfGuardUser")->find($row['id_usuario']);
   		$amigo = Doctrine::getTable("sfGuardUser")->find($row['id_amigo']);
   		try{
   			if(is_object($user) && is_object($amigo))
   				$user->getMainGroup()->addUser($amigo);
   			else throw new Exception("El usuario no existe ");
   		}catch(Exception $e){
   			echo $e->getMessage();
   		}
   	}
   	*/
   	
    
    //Hacer amigos del jabber
    //$users = Doctrine::getTable("sfGuardUser")->findAll();
    
	$query = "Select id from sf_guard_user LIMIT ".$arguments['offset'].",".$arguments['limit'];
   	$result = mysql_query($query,$link);
   	
   	   	                $defaultSounds = array('08c6f6c588dcc5e9c5c654bb25a4397e','0b1e0de1b261b9387a1274dc68104ac5','1716a50c1e08b63c672f9d28b2334e49','1dcfbdbc154d1ba57d400f04ef6ea8a1',
                '267917b10957e8c13f63a22af470bdce','37a1a232113b91337f89e144db96953f','388759c6d3d4297a49890d5b47ad573b','6fa8f24a39701de99da8a9b2c085ee3','827811f71e13b1e14b844ae04c3c62b4',
                '888bc9015075644ea210884c88a03f08','979a386f33c96ae927cb55e806f7db08','9de41a0c3a4a0cb9d0685e4e241853f5','ba3807fb583f82be0a33457f88f29a5b','05c04a1851ceaf091c72919e347ce68',
                'ccaf0eafce551aa21517319771a340c7','cd5f1764617ba8563f79af54acef5029','defa6d743b50b72326440ef4461014cc','df930bf50224cc191ab79b29363d4571');
   	   	                
   	while($row = mysql_fetch_assoc($result)){
   		$user = Doctrine::getTable("sfGuardUser")->find($row['id']);
   		/*echo $user->getUsername()."\n";
   		$pass = md5(rand(1,1000)*rand(1000,10000));
   		LdapLogin::createUser($user->getUsername(), $pass);
   		$user->setPassword($pass);
   		$user->save();*/
    	echo "Usuario ".$user."\n";

                foreach($defaultSounds as $soundId){
                	$soundUser = new SoundUser();
	                $soundUser->setSoundId($soundId);
	                $soundUser->setUserId($user->getId());
	                try{$soundUser->save();}catch(Exception $e){
	                	echo $e->getMessage();
	                	echo "\n\tSonido: ".$soundId;
	                }
                }
    	/*$friends = $user->getMainGroup()->getUsers();
    	foreach($friends as $friend){
	    	$ch = curl_init();
	  		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	  		$url="http://127.0.0.1:9090/plugins/rosterManager/rostermanager?type=create&username=".$user->getUsername()."&jid=".$friend->getUsername()."@wixet.com&secret=".sfConfig::get('sf_openfire_secret');
	        curl_setopt($ch, CURLOPT_URL,$url);
	        $res11 = json_decode(curl_exec ($ch));
	        
	  		$url="http://127.0.0.1:9090/plugins/rosterManager/rostermanager?type=modify&username=".$user->getUsername()."&jid=".$friend->getUsername()."@wixet.com&sub=both&secret=".sfConfig::get('sf_openfire_secret');
	        curl_setopt($ch, CURLOPT_URL,$url);
	        $res12 = json_decode(curl_exec ($ch));
	        echo $friend->getUsername()." ".$res12;	
    	}*/
    }
        
   $this->log("Hecho");
   mysql_close($link);
    // add your code here
  }
}
